<?php
/**
 * @package account
 */
class ConvertGridFieldDataColumns implements GridField_ColumnProvider, GridField_ActionProvider {
    public function augmentColumns($gridField, &$columns) {
        if(!in_array('Actions', $columns)) {
            $columns[] = 'Actions';
        }
    }

    public function getColumnAttributes($gridField, $record, $columnName) {
        return array('class' => 'col-buttons');
    }

    public function getColumnMetadata($gridField, $columnName) {
        if($columnName == 'Actions') {
            return array('title' => '');
        }
    }

    public function getColumnsHandled($gridField) {
        return array('Actions');
    }

    public function getColumnContent($gridField, $record, $columnName) {
    	Requirements::css('account/css/ConvertGridFieldDataColumns.css');
    	$content = '';
    	if($record->canRevert()){
    		$field = GridField_FormAction::create($gridField, 'Revert' . $record->ID, false, "revert", array('RecordID' => $record->ID))->addExtraClass('gridfield-button-revert')->setAttribute('title', _t('ConvertGridFieldDataColumns.BUTTONREVERT', 'Revert'))->setAttribute('data-icon', 'arrow-circle-135-left')->setDescription(_t('ConvertGridFieldDataColumns.REVERT_CONVERT', 'Revert Convert'));
			$content .= $field->Field();
		}
		return $content;
    }

    public function getActions($gridField) {
        return array(
            'revert'
        );
    }

    public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
        if($actionName == 'revert') {
            $item = $gridField->getList()->byID($arguments['RecordID']);
            if(!$item) {
                return;
            }

        	if(!$item->canRevert()) {
                throw new ValidationException(_t('ConvertGridFieldDataColumns.REVERT_PERMISSION', 'No permission to revert these item'), 0);
            }
			
			try {
	            DB::getConn()->transactionStart();
	            $item->IsRevert = 1;
        		$item->write();
	            DB::getConn()->transactionEnd();
	        }
	        catch(ValidationException $e) {
	            DB::getConn()->transactionRollback();
	            throw new ValidationException($e->getMessage(), 0);
	        }
        }
    }
}
